package cc.orange.mainView;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;

import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;

import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.RelativeLayout;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.xcheng.retrofit.Call;
import com.xcheng.retrofit.DefaultCallback;
import com.xcheng.retrofit.HttpError;
import com.xcheng.retrofit.RetrofitFactory;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import cc.orange.BuildConfig;
import cc.orange.R;
import cc.orange.base.BaseFragment;
import cc.orange.databinding.FragmentA12SetBinding;
import cc.orange.entity.BaseEntity;
import cc.orange.entity.HightEntity;
import cc.orange.entity.IsLoginsEntity;
import cc.orange.entity.LoginsEntity;
import cc.orange.entity.MsgLoginUI3Entity;
import cc.orange.entity.SuerInfosEntity;
import cc.orange.entity.UpDataPasPostEntity;
import cc.orange.entity.UpdataUserPostEntity;
import cc.orange.http.ApiService;
import cc.orange.utils.ZXToastUtil;
import cc.orange.utils.popup.AdolescentModelView;
import cc.orange.utils.popup.PopupDiscoView;
import cc.orange.utils.popup.PopupNameView;
import cc.orange.utils.popup.PopupPhonelView;
import demo.smart.access.xutlis.util.ZXSharedPrefUtil;
import okhttp3.MediaType;
import okhttp3.RequestBody;

public class A12SetFragment extends BaseFragment implements View.OnClickListener{
    private boolean isLogin = false;
    private FragmentA12SetBinding binding;
    private ZXSharedPrefUtil sharedPrefUtil;
    private SuerInfosEntity entity;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        binding = DataBindingUtil.inflate(inflater,R.layout.fragment_a12_set,container,false);
        sharedPrefUtil = new ZXSharedPrefUtil();
        isLogin = sharedPrefUtil.getBool("isLogin_hr",false);
        initViews();
        getSuserInfo();
        EventBus.getDefault().register(this);
        return binding.getRoot();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void getHight(HightEntity entity) {//改变布局
        Log.v("---->3",""+entity.getHight());
        if(entity.getHight() > 0){
            RelativeLayout.LayoutParams pp = new RelativeLayout.
                    LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                    entity.getHight());
            binding.msglistTitle.setLayoutParams(pp);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getHight(String entity) {//
        if(entity.equals("getsus")){
            getSuserInfo();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getHight(IsLoginsEntity entity){
        if(!entity.isLogins()){
            isLogin = false;
            binding.setText2.setVisibility(View.GONE);
            binding.setText1.setText("请先登录");
            Glide.with(getActivity()).load(R.drawable.icon_login_img3).into(binding.setImg1);
        }else{
            getSuserInfo();
        }
    }

    private void initViews() {

        if (BuildConfig.UIA.equals("A1")) {// A1面
                binding.face1TitleBack.setBackgroundResource(R.drawable.icon_a1_titleback);
                binding.msglistTitle2.setTextColor(getResources().getColor(R.color.white));
                binding.settRel2Img1.setImageResource(R.drawable.icon_a12set_img4);
                binding.settRel2Img2.setImageResource(R.drawable.icon_a12set_img7);
                binding.settRel2Img3.setImageResource(R.drawable.icon_a12set_img5);

        }else if (BuildConfig.UIA.equals("A2")){// A2面
                binding.face1TitleBack.setBackgroundResource(R.drawable.icon_a2_titleback);
                binding.msglistTitle2.setTextColor(getResources().getColor(R.color.black));

                binding.settRel2Img1.setImageResource(R.drawable.icon_a12set2_img4);
                binding.settRel2Img2.setImageResource(R.drawable.icon_a12set2_img5);
                binding.settRel2Img3.setImageResource(R.drawable.icon_a12set2_img6);
            }


        binding.setImg1.setOnClickListener(this);
        binding.setText2.setOnClickListener(this);
        binding.setA12Rel1.setOnClickListener(this);
        binding.setA12Rel2.setOnClickListener(this);
        binding.setA12Rel3.setOnClickListener(this);
        binding.setA12Rel6.setOnClickListener(this);
        binding.setA12Rel7.setOnClickListener(this);
        binding.setA12Rel8.setOnClickListener(this);
        binding.setA12Rel9.setOnClickListener(this);
        binding.setText3.setOnClickListener(this);
        binding.setA12Rel5.setOnClickListener(this);


        binding.setA12Switch1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                updateNotify(isChecked,1);
            }
        });
        binding.setA12Switch2.setClickable(false);
    }


    private void getSuserInfo(){
        RetrofitFactory.create(ApiService.class)
                .getSuserInfo(getTokens())
                .enqueue(new DefaultCallback<SuerInfosEntity>() {
                    @Override
                    public void onStart(Call<SuerInfosEntity> call) {
                        showLoading_base(getActivity());
                    }

                    @Override
                    public void onError(Call<SuerInfosEntity> call, HttpError error) {
                        cancelLoading();
                        EventBus.getDefault().post(new MsgLoginUI3Entity(true));
                    }

                    @Override
                    public void onSuccess(Call<SuerInfosEntity> call, SuerInfosEntity baseEntity) {
                        cancelLoading();
                        EventBus.getDefault().postSticky(baseEntity);
                        if(baseEntity.getCode() == 0){
                            entity = baseEntity;
                            if(TextUtils.isEmpty(baseEntity.getData().getAddress())){
                                EventBus.getDefault().post(new MsgLoginUI3Entity(true));
                            }else{
                                EventBus.getDefault().post(new MsgLoginUI3Entity(false));
                            }
                            RequestOptions qe = new RequestOptions();
                            qe.error(baseEntity.getData().getSex() == 1 ? R.drawable.icon_a12set_img2:R.drawable.icon_a12set_img3);
                            Glide.with(getActivity()).load(baseEntity.getData().getHeadPhoto()).apply(qe).into(binding.setImg1);
                            if(baseEntity.getData().getIsTeenagers().equals("1")){//是否青少年模式(0不是,1是)
                                binding.setA12Switch2.setChecked(true);
                            }else{
                                binding.setA12Switch2.setChecked(false);
                            }

                            if(baseEntity.getData().getNewsRemind().equals("1")){//是否开启消息提醒(0关闭,1开启)
                                binding.setA12Switch1.setChecked(true);
                            }else{
                                binding.setA12Switch1.setChecked(false);
                            }

                            binding.setText2.setVisibility(View.VISIBLE);
                            binding.setText1.setText(baseEntity.getData().getName());

                            ZXSharedPrefUtil ss = new ZXSharedPrefUtil();
                            ss.putString("url_addres",baseEntity.getData().getAddress());
                            ss.putString("url_sex",""+baseEntity.getData().getSex());
                            ss.putString("url_age",baseEntity.getData().getAge());
                            ss.putString("name_hr",baseEntity.getData().getName());
                            ss.putString("openid_hr",baseEntity.getData().getOpenId());
                            ss.putString("url_hr",baseEntity.getData().getHeadPhoto());
                        }else{
                            EventBus.getDefault().post(new MsgLoginUI3Entity(true));
                            ZXToastUtil.showToast(baseEntity.getMsg());
                        }
                    }
                });
    }

    @Override
    public void onClick(View v) {
        isLogin = sharedPrefUtil.getBool("isLogin_hr",false);
        if(!isLogin &&  v.getId() != R.id.msg_rel2){
            binding.setText2.setVisibility(View.GONE);
            ZXToastUtil.showToast("请先登录");
            startActivity(new Intent(getActivity(),A12LoginActivity.class));
            return;
        }
        switch (v.getId()){
            case R.id.set_img1:
                break;
            case R.id.set_text2://修改昵称
                PopupNameView.showPopupwindow(getActivity(), entity.getData().getName(), binding.msglistTitle,
                        new PopupNameView.PopuStatus() {
                            @Override
                            public void popupShow() {

                            }

                            @Override
                            public void popupDismissCancle(String se1) {
                                updateName(se1);
                            }
                        });
                break;
            case R.id.set_a12_rel1://设置账号
                showPopu(1);
                break;
            case R.id.set_a12_rel2://修改密码
                if(null == entity)return;
                if(!TextUtils.isEmpty(entity.getData().getUserName())){
                    showPopu(2);
                }else{
                    ZXToastUtil.showToast("请先设置账号");
                }
                break;
            case R.id.set_a12_rel3://隐私政策
                WebViewActivity.openH5Activity(getActivity(),"隐私政策",BuildConfig.WEBS_URL2);
                break;
            case R.id.set_a12_rel6://退出登录
                showDialogs(2);
                break;
            case R.id.set_a12_rel7://联系客服
                Intent intent = new Intent(getActivity(), A12ConveKFActivity.class);
                startActivity(intent);
                break;
            case R.id.set_a12_rel8://用户协议
                WebViewActivity.openH5Activity(getActivity(),"用户协议", BuildConfig.WEBS_URL1);
                break;
            case R.id.set_a12_rel9://应用权限说明
                WebViewActivity.openH5Activity(getActivity(),"应用权限说明",BuildConfig.WEBS_URL3);
                break;
            case R.id.set_text3://签名
                break;
            case R.id.set_a12_rel5://青少年模式
            if( binding.setA12Switch2.isChecked()){
                binding.setA12Switch2.setChecked(false);
                updateNotify(false,2);
            }else {
                showPopu2();
            }
                break;
        }
    }


    private void updateNotify(boolean bol,int types){
        UpdataUserPostEntity entitys = new UpdataUserPostEntity();
        if(types == 1){
            entitys.setNewsRemind(bol ? "1":"0");//是否开启消息提醒(0关闭,1开启)
        }else{
            entitys.setIsTeenagers(bol ? "1":"0");//是否青少年模式(0不是,1是)
        }

        Gson gss = new Gson();
        String s = gss.toJson(entitys);
        RequestBody requestBody1 = RequestBody.create(MediaType.parse("application/json"), s.toString());

        RetrofitFactory.create(ApiService.class)
                .updateUser(getTokens(),requestBody1)
                .enqueue(new DefaultCallback<LoginsEntity>() {
                    @Override
                    public void onStart(Call<LoginsEntity> call) {
                        showLoading_base(getActivity());
                    }

                    @Override
                    public void onError(Call<LoginsEntity> call, HttpError error) {
                        cancelLoading();
                    }

                    @Override
                    public void onSuccess(Call<LoginsEntity> call, LoginsEntity baseEntity) {
                        cancelLoading();
                        if(baseEntity.getCode() == 0){
                            ZXToastUtil.showToast("设置成功");
                            getSuserInfo();
                            if(types == 2) {
                                binding.setA12Switch2.setChecked(bol);
                            }
                        }else{
                            ZXToastUtil.showToast(baseEntity.getMsg());
                        }
                    }
                });
    }

    //设置青少年模式
    private void showPopu2(){
        AdolescentModelView.showPopupwindow(getActivity(), binding.msglistTitle, new AdolescentModelView.PopuStatus() {
            @Override
            public void popupShow() {

            }

            @Override
            public void popupDismissCancle2(String se1) {
                if(se1.equals("2")){
                    updateNotify(true,2);
                }
            }
        });
    }


    private void showDialogs(int type){
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());       //
        builder.setTitle("");// 设置对话框的标题
        if(type == 1){
            builder.setMessage("确定要注销账号吗？账号注销后，您的所有信息将被清除");
        }else{
            builder.setMessage("确定要退出登录吗？");
        }

        builder.setNegativeButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if(type == 1){
                    deleteUser();
                }else{
                    ZXSharedPrefUtil ss = new ZXSharedPrefUtil();
                    ss.clear();
                    EventBus.getDefault().post(new IsLoginsEntity(false));
                    binding.setText1.setText("请先登录");
                    binding.setText2.setVisibility(View.GONE);
                    Glide.with(getActivity()).load(R.drawable.icon_login_img3).into(binding.setImg1);
                    ZXToastUtil.showToast("账号已退出");
                    getHight(new IsLoginsEntity(false));
                }
            }
        });
        builder.setPositiveButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        builder.create().show();
    }



    private void deleteUser() {
        RetrofitFactory.create(ApiService.class)
                .deleteUser(getTokens())
                .enqueue(new DefaultCallback<BaseEntity>() {
                    @Override
                    public void onStart(Call<BaseEntity> call) {
                        showLoading_base(getActivity());
                    }

                    @Override
                    public void onError(Call<BaseEntity> call, HttpError error) {
                        cancelLoading();
                    }

                    @Override
                    public void onSuccess(Call<BaseEntity> call, BaseEntity baseEntity) {
                        cancelLoading();
                        if (baseEntity.getCode() == 0) {
                            ZXSharedPrefUtil ss = new ZXSharedPrefUtil();
                            ss.clear();
                            EventBus.getDefault().post(new IsLoginsEntity(false));
                            ZXToastUtil.showToast("账号注销成功");
                            binding.setText1.setText("请先登录");
                            binding.setText2.setVisibility(View.GONE);
                            getHight(new IsLoginsEntity(false));
                            Glide.with(getActivity()).load(R.drawable.icon_login_img3).into(binding.setImg1);
                        } else {
//                            ZXToastUtil.showToast(baseEntity.getMsg());
                        }
                    }
                });
    }


    //设置账号密码
    private void showPopu(int settype){
        PopupDiscoView.showPopupwindow(getActivity(), settype,entity.getData().getUserName(),binding.msglistTitle, new PopupDiscoView.PopuStatus() {
            @Override
            public void popupShow() {

            }

            @Override
            public void popupDismissCancle(String se1, String se2) {
                if(settype == 2){
                    updatePass(se2);
                }else{
                    updateUser(se1,se2);
                }
            }

            @Override
            public void popupDismissCancle2(String se1) {
                showDialogs(1);
            }
        });
    }


    private void updatePass(String psw){
        UpDataPasPostEntity entitys = new UpDataPasPostEntity(psw);
        Gson gss = new Gson();
        String s = gss.toJson(entitys);
        RequestBody requestBody1 = RequestBody.create(MediaType.parse("application/json"), s.toString());

        RetrofitFactory.create(ApiService.class)
                .updatePass(getTokens(),requestBody1)
                .enqueue(new DefaultCallback<BaseEntity>() {
                    @Override
                    public void onStart(Call<BaseEntity> call) {
                        showLoading_base(getActivity());
                    }

                    @Override
                    public void onError(Call<BaseEntity> call, HttpError error) {
                        cancelLoading();
                    }

                    @Override
                    public void onSuccess(Call<BaseEntity> call, BaseEntity baseEntity) {
                        cancelLoading();
                        if(baseEntity.getCode() == 0){
                            ZXToastUtil.showToast("修改成功");
                            getSuserInfo();
                        }else{
                            ZXToastUtil.showToast(baseEntity.getMsg());
                        }
                    }
                });
    }


    private void updateUser(String names, String psw) {
        UpdataUserPostEntity entitys = new UpdataUserPostEntity();
        entitys.setUserName(names);
        entitys.setPassWord(psw);
        Gson gss = new Gson();
        String s = gss.toJson(entitys);
        RequestBody requestBody1 = RequestBody.create(MediaType.parse("application/json"), s.toString());

        RetrofitFactory.create(ApiService.class)
                .updateUser(getTokens(),requestBody1)
                .enqueue(new DefaultCallback<LoginsEntity>() {
                    @Override
                    public void onStart(Call<LoginsEntity> call) {
                        showLoading_base(getActivity());
                    }

                    @Override
                    public void onError(Call<LoginsEntity> call, HttpError error) {
                        cancelLoading();
                    }

                    @Override
                    public void onSuccess(Call<LoginsEntity> call, LoginsEntity baseEntity) {
                        cancelLoading();
                        if(baseEntity.getCode() == 0){
                            ZXToastUtil.showToast("设置成功");
                            getSuserInfo();
                        }else{
                            if(baseEntity.getMsg().contains("此账号已经被注册")){
                                PopupPhonelView.showPopupwindow(getActivity(), binding.msglistTitle, new PopupPhonelView.PopuStatus() {
                                    @Override
                                    public void popupShow() {

                                    }

                                    @Override
                                    public void popupDismissCancle2(String se1) {
                                        showPopu(1);
                                    }
                                });
                            }
                            ZXToastUtil.showToast(baseEntity.getMsg());
                        }
                    }
                });
    }


    private void updateName(String name){
        UpdataUserPostEntity entitys = new UpdataUserPostEntity();
        entitys.setName(name);
        Gson gss = new Gson();
        String s = gss.toJson(entitys);
        RequestBody requestBody1 = RequestBody.create(MediaType.parse("application/json"), s.toString());

        RetrofitFactory.create(ApiService.class)
                .updateUser(getTokens(),requestBody1)
                .enqueue(new DefaultCallback<LoginsEntity>() {
                    @Override
                    public void onStart(Call<LoginsEntity> call) {
                        showLoading_base(getActivity());
                    }

                    @Override
                    public void onError(Call<LoginsEntity> call, HttpError error) {
                        cancelLoading();
                    }

                    @Override
                    public void onSuccess(Call<LoginsEntity> call, LoginsEntity baseEntity) {
                        cancelLoading();
                        if(baseEntity.getCode() == 0){
                            ZXToastUtil.showToast("设置成功");
                            getSuserInfo();
                            binding.setText1.setText(name);
                            entity.getData().setName(name);
                        }else{
                            ZXToastUtil.showToast(baseEntity.getMsg());
                        }
                    }
                });
    }

}